package com.software.loginregister.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.gson.Gson;
import com.google.protobuf.Api;
import com.software.loginregister.R;
import com.software.loginregister.adapter.CommentAdapter;
import com.software.loginregister.adapter.IngredientAdapter;
import com.software.loginregister.adapter.StepAdapter;
import com.software.loginregister.api.CommentApi;
import com.software.loginregister.api.LikeApi;
import com.software.loginregister.api.UserRelationApi;
import com.software.loginregister.api.WorksApi;
import com.software.loginregister.databasesHelper.AppDatabase;
import com.software.loginregister.databasesHelper.WorksCacheDao;
import com.software.loginregister.entity.Comment;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.Step;
import com.software.loginregister.entity.Works;
import com.software.loginregister.entity.room.WorksCache;
import com.software.loginregister.entity.vo.CookingStepVO;
import com.software.loginregister.entity.vo.IngredientDTO;
import com.software.loginregister.entity.vo.UserUpdateDTO;
import com.software.loginregister.util.HistoryManager;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RecommendDetailActivity extends AppCompatActivity {
    private ImageView ivWorkDetail;
    private ImageView ivUserAvatar;
    private TextView tvWorkName;
    private TextView tvNeckName;
    private TextView tvLikeCount;
    private ImageButton ivLike;
    private Button btnFollow;
    private TextView tvDescription;
    private RecyclerView rvIngredients;
    private IngredientAdapter ingredientAdapter;
    private boolean isLiked = false;
    private int likeCount = 0;
    private boolean isFollowed = false;
    private RecyclerView rvSteps;
    private StepAdapter stepAdapter;
    private List<Step> stepsList;
    private Long worksId;
    private String avatar;

    private Long targetUserId;
    private Long currentUserId;
    private UserRelationApi userRelationApi;

    // Comment related variables
    private BottomSheetBehavior<LinearLayout> bottomSheetBehavior;
    private RecyclerView commentList;
    private EditText commentInput;
    private Button submitComment;
    private CommentAdapter commentAdapter;
    private Long targetId;
    private TextToSpeech tts;
    private ImageView ivVoicePlay;
    private boolean isSpeaking = false;

    private HistoryManager historyManager;
    private Works currentWork;
    private WorksCacheDao worksCacheDao;
    private Gson gson;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recommend_detail);

        setStatusBar();
        userRelationApi = RetrofitClient.getInstance().create(UserRelationApi.class);

        UserUpdateDTO userInfo = SharedPreferencesUtil.getUserInfo(this);
        if (userInfo != null) {
            currentUserId = userInfo.getUserId();
        }

        initViews();

        loadWorkData();
        if (currentUserId != null && currentUserId != 0 &&
                targetUserId != null && targetUserId != 0) {
            Log.d("RecommendDetailActivityDebug", "页面加载时检查关注状态");
            checkFollowStatus();
        }
        loadIngredientsData();
        loadStepsData();
        loadUserAvatar(avatar);
        setupListeners();
        checkLikeStatus();
        initCommentSection();
        loadComments();

        historyManager = new HistoryManager(this);
        gson = new Gson();

        // Assume you're getting the work from the intent
        String workJson = getIntent().getStringExtra("work");
        if (workJson != null) {
            currentWork = gson.fromJson(workJson, Works.class);
            if (currentWork != null) {
                // Add the current work to browsing history
                historyManager.addToHistory(currentWork);

                // Display work details
                displayWorkDetails();
            }
        }

        worksCacheDao = AppDatabase.getDatabase(this).worksCacheDao();
        gson = new Gson();

        // 从 Intent 中获取作品信息
        int worksId = getIntent().getIntExtra("worksId", 0);
        Log.d("RecommendDetailActivity", "接收到的作品ID: " + worksId);
        String worksName = getIntent().getStringExtra("worksName");
        String photoUrl = getIntent().getStringExtra("photoUrl");
        String description = getIntent().getStringExtra("description");
        int userId = getIntent().getIntExtra("userId", 0);
        String difficulty = getIntent().getStringExtra("difficulty");
        int recipeId = getIntent().getIntExtra("recipeId", 0);
        int commentCount = getIntent().getIntExtra("commentCount", 0);
        int likeCount = getIntent().getIntExtra("likeCount", 0);
        int pageView = getIntent().getIntExtra("pageView", 0);
        String userName = getIntent().getStringExtra("userName");
        String mainIngredients = getIntent().getStringExtra("mainIngredients");
        String nutrition = getIntent().getStringExtra("nutrition");
        String steps = getIntent().getStringExtra("steps");

        currentWork = new Works();
        currentWork.setWorksId(worksId);
        currentWork.setWorksName(worksName);
        currentWork.setPhotoUrl(photoUrl);
        currentWork.setDescription(description);
        currentWork.setUserId(userId);
        currentWork.setDifficulty(difficulty);
        currentWork.setRecipeId(recipeId);
        currentWork.setCommentCount(commentCount);
        currentWork.setLikeCount(likeCount);
        currentWork.setPageView(pageView);
        currentWork.setUserName(userName);
        currentWork.setMainIngredients(mainIngredients);
        currentWork.setNutrition(nutrition);
        currentWork.setSteps(steps);
        currentWork.setUpdateTime(new Date()); // Set current time as update time

        // 保存到缓存
        saveToCache();

        // 更新页面浏览量
        updatePageView();

        // 显示作品详情
        displayWorkDetails();
    }

    private void displayWorkDetails() {
        if (currentWork != null) {
            tvWorkName.setText(currentWork.getWorksName());
            tvDescription.setText(currentWork.getDescription());

            Glide.with(this)
                    .load(currentWork.getPhotoUrl())
                    .placeholder(R.drawable.ic_food)
                    .error(R.drawable.ic_food)
                    .into(ivWorkDetail);

            // Increase view count
            increaseViewCount(currentWork.getWorksId().intValue());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (currentUserId != null && currentUserId != 0 &&
                targetUserId != null && targetUserId != 0) {
            checkFollowStatus();
        }
    }

    private void setStatusBar() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);

        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);
    }

    private void initViews() {
        ImageView ivBack = findViewById(R.id.iv_back);
        ivWorkDetail = findViewById(R.id.iv_work_detail);
        tvWorkName = findViewById(R.id.tv_work_name);
        tvLikeCount = findViewById(R.id.tv_like_count);
        ivUserAvatar = findViewById(R.id.iv_user_avatar);
        tvNeckName = findViewById(R.id.tv_neck_name);
        btnFollow = findViewById(R.id.btn_follow);
        tvDescription = findViewById(R.id.tv_description);
        ivLike = findViewById(R.id.iv_like);
        rvIngredients = findViewById(R.id.rv_ingredients);
        rvIngredients.setLayoutManager(new LinearLayoutManager(this));
        rvSteps = findViewById(R.id.rv_steps);
        rvSteps.setLayoutManager(new LinearLayoutManager(this));
        stepsList = new ArrayList<>();
        stepAdapter = new StepAdapter(this, stepsList);
        rvSteps.setAdapter(stepAdapter);

        // Comment related views
        LinearLayout bottomSheet = findViewById(R.id.bottomSheet);
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
        commentList = findViewById(R.id.commentList);
        commentInput = findViewById(R.id.commentInput);
        submitComment = findViewById(R.id.submitComment);

        if (ivBack != null) {
            ivBack.setOnClickListener(v -> finish());
        }
        ivVoicePlay = findViewById(R.id.iv_voice_play);
        ivVoicePlay.setOnClickListener(v -> toggleSpeech());

        // 初始化 TextToSpeech
        tts = new TextToSpeech(this, status -> {
            if (status == TextToSpeech.SUCCESS) {
                int result = tts.setLanguage(Locale.CHINESE);
                if (result == TextToSpeech.LANG_MISSING_DATA ||
                        result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Toast.makeText(RecommendDetailActivity.this,
                            "语言包不支持", Toast.LENGTH_SHORT).show();
                    ivVoicePlay.setEnabled(false);
                }
            } else {
                Toast.makeText(RecommendDetailActivity.this,
                        "语音初始化失败", Toast.LENGTH_SHORT).show();
                ivVoicePlay.setEnabled(false);
            }
        });
    }


    // 添加语音播报相关方法
    private void toggleSpeech() {
        if (isSpeaking) {
            stopSpeaking();
        } else {
            startSpeaking();
        }
    }


    private void startSpeaking() {
        StringBuilder content = new StringBuilder();
        content.append(tvWorkName.getText()).append("。");
        content.append("食材准备：");

        // 获取食材列表
        if (ingredientAdapter != null && ingredientAdapter.getItemCount() > 0) {
            List<IngredientDTO> ingredients = ingredientAdapter.getAllIngredients();
            for (IngredientDTO ingredient : ingredients) {
                content.append(ingredient.getIngredientName())
                        .append(ingredient.getAmount() != null ? ingredient.getAmount() : "适量")
                        .append(ingredient.getUnit())
                        .append("。");
            }
        }

        content.append("制作步骤：");
        // 获取步骤列表
        if (stepsList != null && !stepsList.isEmpty()) {
            for (Step step : stepsList) {
                content.append("第")
                        .append(step.getStepNumber())
                        .append("步，")
                        .append(step.getDescription())
                        .append("。");
            }
        }

        // 更新UI状态
        ivVoicePlay.setImageResource(R.drawable.ic_voice_playing); // 需要添加播放中的图标
        isSpeaking = true;

        // 设置播报完成的监听
        tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onStart(String utteranceId) {}

            @Override
            public void onDone(String utteranceId) {
                runOnUiThread(() -> stopSpeaking());
            }

            @Override
            public void onError(String utteranceId) {
                runOnUiThread(() -> stopSpeaking());
            }
        });

        // 开始播报
        Bundle params = new Bundle();
        params.putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, 1.0f);
        tts.speak(content.toString(), TextToSpeech.QUEUE_FLUSH, params, "RecipeUtterance");
    }

    private void stopSpeaking() {
        if (tts != null) {
            tts.stop();
        }
        ivVoicePlay.setImageResource(R.drawable.ic_voice_play); // 需要添加正常状态的图标
        isSpeaking = false;
    }
    // 在 onDestroy() 中释放资源
    @Override
    protected void onDestroy() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }

    private void loadWorkData() {
        Intent intent = getIntent();
        worksId = intent.getLongExtra("worksId", 0);
        String worksName = intent.getStringExtra("worksName");
        String nickname = intent.getStringExtra("nickname");
        String photoUrl = intent.getStringExtra("photoUrl");
        avatar = intent.getStringExtra("avatar");
        String description = intent.getStringExtra("description");
//        tvLikeCount.setText(String.valueOf(likeCount));
        //获取点赞数
        getLikeCount(new LikeCountCallback() {
            @Override
            public void onLikeCountReceived(int count) {
                likeCount = count;
            }
        });
        updateLikeStatus(likeCount);

        targetUserId = (long) intent.getIntExtra("userId", -1);
        Log.d("RecommendDetailActivityDebug", "传输userid:"+targetUserId);


        tvWorkName.setText(worksName);
        tvNeckName.setText(nickname);

        tvDescription.setText(description);

        if (!TextUtils.isEmpty(photoUrl)) {
            Glide.with(this)
                    .load(photoUrl)
                    .placeholder(R.drawable.image_loading)
                    .error(R.drawable.ic_defalut_avater)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(ivWorkDetail);
        } else {
            ivWorkDetail.setImageResource(R.mipmap.ic_aicooking);
        }
    }

    private void loadUserAvatar(String avatarUrl) {
        Log.d("RecommendDetailActivityDebug", "开始加载用户头像: " + avatarUrl);

        if (!TextUtils.isEmpty(avatarUrl)) {
            Glide.with(this)
                    .load(avatarUrl)
                    .placeholder(R.mipmap.ic_aicooking)
                    .error(R.mipmap.ic_aicooking)
                    .circleCrop()
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e,
                                                    Object model, Target<Drawable> target, boolean isFirstResource) {
                            Log.e("RecommendDetailActivityDebug", "头像加载失败", e);
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model,
                                                       Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            Log.d("RecommendDetailActivityDebug", "头像加载成功");
                            return false;
                        }
                    })
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .skipMemoryCache(false)
                    .into(ivUserAvatar);
        } else {
            Log.d("RecommendDetailActivityDebug", "头像URL为空，使用默认图片");
            ivUserAvatar.setImageResource(R.mipmap.ic_aicooking);
        }
    }

    private void loadIngredientsData() {
        if (worksId == 0) {
            Log.d("RecommendDetailActivityDebug", "作品id无效:" + worksId);
            return;
        }
        RetrofitClient.getInstance()
                .create(WorksApi.class)
                .getRecipeIngredients(worksId.intValue())
                .enqueue(new Callback<Result<List<IngredientDTO>>>() {
                    @Override
                    public void onResponse(Call<Result<List<IngredientDTO>>> call,
                                           Response<Result<List<IngredientDTO>>> response) {
                        if (response.isSuccessful() && response.body() != null
                                && response.body().getData() != null) {
                            List<IngredientDTO> ingredients = response.body().getData();
                            ingredientAdapter = new IngredientAdapter(ingredients);
                            rvIngredients.setAdapter(ingredientAdapter);
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<List<IngredientDTO>>> call, Throwable t) {
                        Log.e("RecommendDetailActivityDebug", "获取食材列表失败", t);
                        Toast.makeText(RecommendDetailActivity.this,
                                "获取食材信息失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void loadStepsData() {
        if (worksId == 0) {
            Toast.makeText(this, "作品ID无效", Toast.LENGTH_SHORT).show();
            return;
        }

        showLoading();
        RetrofitClient.getInstance()
                .create(WorksApi.class)
                .getSteps(worksId)
                .enqueue(new Callback<Result<List<CookingStepVO>>>() {
                    @Override
                    public void onResponse(Call<Result<List<CookingStepVO>>> call,
                                           Response<Result<List<CookingStepVO>>> response) {
                        hideLoading();
                        if (response.isSuccessful() && response.body() != null) {
                            Result<List<CookingStepVO>> result = response.body();
                            if (result.getCode() == 1 && result.getData() != null) {
                                stepsList.clear();
                                for (CookingStepVO stepVO : result.getData()) {
                                    if (!TextUtils.isEmpty(stepVO.getPhotoUrl())) {
                                        stepsList.add(new Step(
                                                stepVO.getStepNumber(),
                                                stepVO.getDescription(),
                                                stepVO.getPhotoUrl()
                                        ));
                                    } else {
                                        stepsList.add(new Step(
                                                stepVO.getStepNumber(),
                                                stepVO.getDescription(),
                                                R.drawable.ic_food
                                        ));
                                    }
                                }
                                stepAdapter.notifyDataSetChanged();
                            } else {
                                loadDefaultSteps();
                                Toast.makeText(RecommendDetailActivity.this,
                                        result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            loadDefaultSteps();
                            Toast.makeText(RecommendDetailActivity.this,
                                    "获取步骤失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<List<CookingStepVO>>> call, Throwable t) {
                        hideLoading();
                        loadDefaultSteps();
                        Toast.makeText(RecommendDetailActivity.this,
                                "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void loadDefaultSteps() {
        stepsList.clear();
        stepsList.add(new Step(1, "准备所需食材，清洗处理", R.drawable.ic_food));
        stepsList.add(new Step(2, "食材切块，调制调味料", R.drawable.ic_food));
        stepsList.add(new Step(3, "热锅下油，爆香调味料", R.drawable.ic_food));
        stepsList.add(new Step(4, "加入主料翻炒", R.drawable.ic_food));
        stepsList.add(new Step(5, "加入适量水，焖煮收汁", R.drawable.ic_food));
        stepsList.add(new Step(6, "调味后装盘即可", R.drawable.ic_food));
        stepAdapter.notifyDataSetChanged();
    }

    private void showLoading() {
        // 实现显示加载进度的逻辑
    }

    private void hideLoading() {
        // 实现隐藏加载进度的逻辑
    }

    private void setupListeners() {
        if (btnFollow != null) {
            btnFollow.setOnClickListener(v -> toggleFollow());
        }
        ivLike.setOnClickListener(v -> toggleLike());
    }

    private void toggleFollow() {
        Log.d("RecommendDetailActivityDebug", "toggleFollow - currentUserId: " + currentUserId);
        Log.d("RecommendDetailActivityDebug", "toggleFollow - targetUserId: " + targetUserId);
        if (currentUserId == null || currentUserId == 0) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        if (targetUserId == null || targetUserId == 0) {
            Log.e("RecommendDetailActivityDebug", "作者ID无效 - targetUserId: " + targetUserId);
            Toast.makeText(this, "作者信息无效2", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查是否是自己
        if (currentUserId.equals(targetUserId)) {
            Toast.makeText(this, "不能关注自己", Toast.LENGTH_SHORT).show();
            return;
        }

        // 禁用按钮防止重复点击
        btnFollow.setEnabled(false);


        userRelationApi.toggleFollow(targetUserId, currentUserId)
                .enqueue(new Callback<Result<Map<String, Object>>>() {
                    @Override
                    public void onResponse(Call<Result<Map<String, Object>>> call,
                                           Response<Result<Map<String, Object>>> response) {
                        btnFollow.setEnabled(true);

                        if (response.isSuccessful() && response.body() != null) {
                            Result<Map<String, Object>> result = response.body();
                            if (result.getCode() == 1 && result.getData() != null) {
                                // 更新关注状态
                                isFollowed = (Boolean) result.getData().get("following");
                                updateFollowStatus();

                                // 显示操作结果
                                String message = (String) result.getData().get("message");
                                Toast.makeText(RecommendDetailActivity.this,
                                        message, Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(RecommendDetailActivity.this,
                                        "操作失败", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(RecommendDetailActivity.this,
                                    "网络请求失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Map<String, Object>>> call, Throwable t) {
                        btnFollow.setEnabled(true);
                        Toast.makeText(RecommendDetailActivity.this,
                                "网络错误", Toast.LENGTH_SHORT).show();
                        Log.d("RecommendDetailActivityDebug", "关注操作失败", t);
                    }
                });
    }

    private void checkFollowStatus() {
        Log.d("RecommendDetailActivityDebug",
                "检查关注状态: currentUserId=" + currentUserId + ", targetId=" + targetUserId);

        userRelationApi.checkFollowStatus(targetUserId, String.valueOf(currentUserId))
                .enqueue(new Callback<Result<Boolean>>() {
                    @Override
                    public void onResponse(Call<Result<Boolean>> call,
                                           Response<Result<Boolean>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            Result<Boolean> result = response.body();

                            if (result.getCode() == 1) {
                                isFollowed = result.getData();
                                runOnUiThread(() -> updateFollowStatus());
                            }
                        } else {
                            Log.d("RecommendDetailActivityDebug",
                                    "检查关注状态失败: " + response.message());
                        }
                    }
                    @Override
                    public void onFailure(Call<Result<Boolean>> call, Throwable t) {
                        Log.e("RecommendDetailActivityDebug", "检查关注状态网络请求失败", t);
                    }
                });
    }

    private void toggleLike() {
        if (currentUserId == null || currentUserId == 0) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        if (worksId == null || worksId == 0) {
            Toast.makeText(this, "作品信息无效", Toast.LENGTH_SHORT).show();
            return;
        }
        ivLike.setEnabled(false);
        targetId = worksId;
        RetrofitClient.getInstance()
                .create(LikeApi.class)
                .toggleLike(currentUserId, targetId, "work")
                .enqueue(new Callback<Result<Map<String, Object>>>() {
                    @Override
                    public void onResponse(Call<Result<Map<String, Object>>> call,
                                           Response<Result<Map<String, Object>>> response) {
                        ivLike.setEnabled(true);

                        if (response.isSuccessful() && response.body() != null) {
                            Result<Map<String, Object>> result = response.body();
                            if (result.getCode() == 1 && result.getData() != null) {
                                isLiked = (Boolean) result.getData().get("liked");
                                int newLikeCount = ((Number) result.getData().get("likeCount")).intValue();
                                updateLikeStatus(newLikeCount);
                                String message = (String) result.getData().get("message");
                                Toast.makeText(RecommendDetailActivity.this, message, Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(RecommendDetailActivity.this, "操作失败: " + result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            try {
                                String errorBody = response.errorBody().string();
                                Log.e("RecommendDetailActivityDebug", "Error body: " + errorBody);
                                Toast.makeText(RecommendDetailActivity.this, "请求失败: " + response.code(), Toast.LENGTH_SHORT).show();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Map<String, Object>>> call, Throwable t) {
                        ivLike.setEnabled(true);
                        Toast.makeText(RecommendDetailActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.e("RecommendDetailActivityDebug", "点赞操作失败", t);
                    }
                });
    }


    private void checkLikeStatus() {
        if (currentUserId == null || currentUserId == 0) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        if (worksId == null || worksId == 0) {
            Toast.makeText(this, "作品信息无效", Toast.LENGTH_SHORT).show();
            return;
        }

        RetrofitClient.getInstance()
                .create(LikeApi.class)
                .isLiked(worksId, currentUserId, "work")
                .enqueue(new Callback<Result<Boolean>>() {
                    @Override
                    public void onResponse(Call<Result<Boolean>> call,
                                           Response<Result<Boolean>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            Result<Boolean> result = response.body();
                            if (result.getCode() == 1 && result.getData() != null) {
                                isLiked = result.getData();
                                getLikeCount(new LikeCountCallback() {
                                    @Override
                                    public void onLikeCountReceived(int count) {
                                        updateLikeStatus(count);
                                    }
                                });
                            } else {
                                Toast.makeText(RecommendDetailActivity.this, "获取点赞状态失败: " + result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            try {
                                String errorBody = response.errorBody().string();
                                Log.e("RecommendDetailActivityDebug", "错误信息: " + errorBody);
                                Toast.makeText(RecommendDetailActivity.this, "请求失败: " + response.code(), Toast.LENGTH_SHORT).show();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Boolean>> call, Throwable t) {
                        Toast.makeText(RecommendDetailActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.e("RecommendDetailActivityDebug", "获取点赞状态失败", t);
                    }
                });
    }
    // 修改 getLikeCount 方法定义
    private void getLikeCount(LikeCountCallback callback) {
        if (worksId == null || worksId == 0) {
            Toast.makeText(this, "作品信息无效", Toast.LENGTH_SHORT).show();
            callback.onLikeCountReceived(0);
            return;
        }

        RetrofitClient.getInstance()
                .create(LikeApi.class)
                .getLikeCount(worksId, "work")
                .enqueue(new Callback<Result<Integer>>() {
                    @Override
                    public void onResponse(Call<Result<Integer>> call,
                                           Response<Result<Integer>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            Result<Integer> result = response.body();
                            if (result.getCode() == 1 && result.getData() != null) {
                                callback.onLikeCountReceived(result.getData());
                            } else {
                                Toast.makeText(RecommendDetailActivity.this, "获取点赞数量失败: " + result.getMsg(), Toast.LENGTH_SHORT).show();
                                callback.onLikeCountReceived(0);
                            }
                        } else {
                            try {
                                String errorBody = response.errorBody().string();
                                Log.e("RecommendDetailActivityDebug", "错误信息: " + errorBody);
                                Toast.makeText(RecommendDetailActivity.this, "请求失败: " + response.code(), Toast.LENGTH_SHORT).show();
                                callback.onLikeCountReceived(0);
                            } catch (IOException e) {
                                e.printStackTrace();
                                callback.onLikeCountReceived(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Integer>> call, Throwable t) {
                        Toast.makeText(RecommendDetailActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.e("RecommendDetailActivityDebug", "获取点赞数量失败", t);
                        callback.onLikeCountReceived(0);
                    }
                });
    }

    // 确保接口定义存在
    public interface LikeCountCallback {
        void onLikeCountReceived(int count);
    }

    private void updateLikeStatus(int newLikeCount) {
        ivLike.setImageResource(isLiked ? R.drawable.ic_heart_filled : R.drawable.ic_heart_outline);
        tvLikeCount.setText(String.valueOf(newLikeCount));

        ivLike.animate()
                .scaleX(1.2f)
                .scaleY(1.2f)
                .setDuration(100)
                .setInterpolator(new OvershootInterpolator())
                .withEndAction(() -> {
                    ivLike.animate()
                            .scaleX(1f)
                            .scaleY(1f)
                            .setDuration(100)
                            .start();
                })
                .start();
    }

    private void updateFollowStatus() {
        btnFollow.setSelected(isFollowed);
        btnFollow.setText(isFollowed ? "已关注" : "关注");
        btnFollow.setBackgroundResource(isFollowed ?
                R.drawable.bg_button_followed_selector :
                R.drawable.bg_button_follow_selector);

        btnFollow.setTextColor(getResources().getColorStateList(R.color.text_follow_button_color));
        btnFollow.animate()
                .scaleX(1f)
                .scaleY(1f)
                .setDuration(200)
                .setInterpolator(new OvershootInterpolator())
                .start();
    }

    private void initCommentSection() {
        commentList.setLayoutManager(new LinearLayoutManager(this));

        commentAdapter = new CommentAdapter(this, new ArrayList<>(), new CommentAdapter.OnCommentActionListener() {


            @Override
            public void onLikeClick(Comment comment, int position) {
                toggleCommentLike(comment, position);
            }
            @Override
            public void onUserClick(Integer userId) {
                navigateToUserProfile(userId);
            }
        });

        commentList.setAdapter(commentAdapter);

        submitComment.setOnClickListener(v -> {
            String content = commentInput.getText().toString().trim();
            if (TextUtils.isEmpty(content)) {
                Toast.makeText(this, "请输入评论内容", Toast.LENGTH_SHORT).show();
                return;
            }

            postComment(content);
        });

        findViewById(R.id.commentHeader).setOnClickListener(v -> {
            if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED) {
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            } else {
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            }
        });
    }

    private static final String TAG = RecommendDetailActivity.class.getSimpleName();
    private void loadComments() {
        RetrofitClient.getInstance()
                .create(CommentApi.class)
                .getComments(worksId)
                .enqueue(new Callback<Result<List<Comment>>>() {
                    @Override
                    public void onResponse(Call<Result<List<Comment>>> call, Response<Result<List<Comment>>> response) {

                        if (response.isSuccessful() && response.body() != null) {
                            Result<List<Comment>> result = response.body();
                            if (result.getCode() == 1 && result.getData() != null) {
                                commentAdapter.setComments(result.getData());
                                commentAdapter.notifyDataSetChanged();
                            } else {
                                Log.e(TAG, "加载评论失败: " + result.getMsg());
                                Toast.makeText(RecommendDetailActivity.this, "加载评论失败: " + result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Log.e(TAG, "加载评论失败: 服务器错误 " + response.code());
                            Toast.makeText(RecommendDetailActivity.this, "加载评论失败: 服务器错误", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<List<Comment>>> call, Throwable t) {
                        Log.e(TAG, "加载评论失败: 网络错误", t);
                        Toast.makeText(RecommendDetailActivity.this, "加载评论失败: 网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void postComment(String content) {
        Comment comment = new Comment();
        comment.setUserId(currentUserId.intValue());
        comment.setWorksId(worksId.intValue());
        comment.setContent(content);

        RetrofitClient.getInstance()
                .create(CommentApi.class)
                .postComment(comment)  // 直接使用 Comment 对象
                .enqueue(new Callback<Result<Comment>>() {
                    @Override
                    public void onResponse(Call<Result<Comment>> call, Response<Result<Comment>> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().getCode() == 1) {
                            Comment newComment = response.body().getData();
                            commentAdapter.addComment(newComment);
                            commentInput.setText("");
                            Toast.makeText(RecommendDetailActivity.this, "评论成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(RecommendDetailActivity.this, "评论失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Comment>> call, Throwable t) {
                        Toast.makeText(RecommendDetailActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void toggleCommentLike(Comment comment, int position) {
        RetrofitClient.getInstance()
                .create(CommentApi.class)
                .toggleCommentLike(comment.getCommentId(), currentUserId.intValue())
                .enqueue(new Callback<Result<Map<String, Object>>>() {
                    @Override
                    public void onResponse(Call<Result<Map<String, Object>>> call, Response<Result<Map<String, Object>>> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().getCode() == 1) {
                            Map<String, Object> data = response.body().getData();
                            comment.setLikesCount(((Number) data.get("likesCount")).intValue());
                            commentAdapter.updateComment(comment, position);
                        }else {
                            Toast.makeText(RecommendDetailActivity.this, "点赞评论失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Map<String, Object>>> call, Throwable t) {
                        Toast.makeText(RecommendDetailActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void navigateToUserProfile(Integer userId) {
        Toast.makeText(this, "跳转到用户ID为 " + userId + " 的主页", Toast.LENGTH_SHORT).show();
    }

    private void increaseViewCount(int worksId) {
        RetrofitClient.getInstance()
                .create(WorksApi.class)
                .increaseViewCount(worksId)
                .enqueue(new Callback<Result<Void>>() {
                    @Override
                    public void onResponse(Call<Result<Void>> call, Response<Result<Void>> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().getCode() == 1) {
                            // View count increased successfully
                        } else {
                            Log.e("RecommendDetailActivity", "Failed to increase view count");
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Void>> call, Throwable t) {
                        Log.e("RecommendDetailActivity", "Network error when increasing view count", t);
                    }
                });
    }

    private void saveToCache() {
        if (currentWork != null) {
            new Thread(() -> {
                try {
                    WorksCache worksCache = new WorksCache();
                    worksCache.setWorksId(currentWork.getWorksId());
                    worksCache.setCacheData(gson.toJson(currentWork));
                    worksCache.setTimestamp(System.currentTimeMillis());
                    worksCacheDao.insertAll(Collections.singletonList(worksCache));
                } catch (Exception e) {
                    Log.e("RecommendDetailActivity", "Error saving to cache", e);
                }
            }).start();
        }
    }
    private void updatePageView() {
        // 增加页面浏览量
        currentWork.setPageView(currentWork.getPageView() + 1);
        // 这里应该有一个 API 调用来更新服务器端的浏览量
        // updatePageViewOnServer(currentWork.getWorksId(), currentWork.getPageView());
    }

}

